export default {
  findMostRelevant(input, dataArray) {
    if (!input || !dataArray?.length) return null;

    const keywords = this.normalizeInput(input);
    let maxScore = 0;
    let result = null;

    dataArray.forEach(item => {
      const [contentPart, resPart] = item.split(/\resStart:\[/);
      const { title, synonyms, fullText } = this.parseContent(contentPart);
      const resTitles = this.parseResTitles(resPart); // 新增资源标题解析
      
      const score = this.calculateScore(
        keywords,
        title,
        synonyms,
        fullText,
        resTitles // 新增资源标题参数
      );

      if (score > maxScore || (score === maxScore && !result)) {
        maxScore = score;
        result = item;
      }
    });

    return result;
  },

  // 新增：解析资源标题
  parseResTitles(resPart) {
    try {
      if (!resPart) return [];
      const resources = JSON.parse(`[${resPart.replace(/\resStart:\[/, '')}]`);
      return resources
        .filter(r => r.title)
        .map(r => r.title.toLowerCase());
    } catch (e) {
      console.warn('资源解析失败:', e);
      return [];
    }
  },

  // 修改后的评分算法
  calculateScore(keywords, title, synonyms, fullText, resTitles) {
    let score = 0;
    
    // 1. 资源标题优先匹配（最高权重）
    resTitles.forEach(resTitle => {
      if (resTitle === keywords.original) score += 100; // 完全匹配
      if (resTitle.includes(keywords.original)) score += 80; // 包含完整关键词
      keywords.words.forEach(word => {
        if (resTitle.includes(word)) score += 50; // 包含关键词片段
      });
    });

    // 2. 主标题匹配
    if (title === keywords.original) score += 60;
    if (title.includes(keywords.original)) score += 50;
    keywords.words.forEach(word => {
      if (title.includes(word)) score += 30;
    });

    // 3. 同义词匹配
    synonyms.forEach(syn => {
      if (syn === keywords.original) score += 40;
      if (syn.includes(keywords.original)) score += 30;
      keywords.words.forEach(word => {
        if (syn.includes(word)) score += 20;
      });
    });

    // 4. 全文匹配
    if (fullText.includes(keywords.original)) score += 30;
    keywords.words.forEach(word => {
      const count = (fullText.match(new RegExp(word, 'g')))?.length || 0;
      score += count * 5;
    });

    return score;
  },

  // 以下方法保持不变
  normalizeInput(input) {
    return {
      original: input.trim().toLowerCase(),
      words: input
        .toLowerCase()
        .split(/[\s\u3000]+/)
        .filter(w => w)
    };
  },

  parseContent(content) {
    const titleMatch = content.match(/^([^(（]+)[（(]/)?.[1] || content.split(/\s/)[0];
    const title = titleMatch.trim();
    
    const synonyms = [];
    const synonymMatch = content.match(/[（(]([^）)]+)[）)]/);
    if (synonymMatch) {
      synonyms.push(...synonymMatch[1].split(/[、,]/g).map(s => s.trim()));
    }

    return {
      title: title.toLowerCase(),
      synonyms: synonyms.map(s => s.toLowerCase()),
      fullText: content.toLowerCase()
    };
  }
};